﻿#region Header
// Copyright 2007-2011, Jerónimo Milea
// 
// This file is part of NetJsWire.
// 
//     NetJsWire is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
// 
//     NetJsWire is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
// 
//     You should have received a copy of the GNU General Public License
//     along with NetJsWire.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System.ComponentModel;
using NetJsWire.Lite.Converters;
using NetJsWire.Lite.Widgets.UI.Util;
using Newtonsoft.Json;

namespace NetJsWire.Lite.Widgets.UI.Data
{
    [JsonObject( MemberSerialization = MemberSerialization.OptIn )]
    public abstract class DataProxy : BaseObservable
    {
        private Api _api = new Api();

        ///<summary>
        ///  Initializes a new instance of DataProxy.
        ///</summary>
        public DataProxy()
            : this( null )
        {
        }

        ///<summary>
        ///  Initializes a new instance of DataProxy and adds it to the Container.
        ///</summary>
        ///<param name = "container"></param>
        public DataProxy( IContainer container )
        {
            if ( container != null )
                container.Add( this );
        }

        [JsonProperty( "api" )]
        [TypeConverter( typeof( ExpandableObjectConverter ) )]
        public Api Api
        {
            get { return _api; }
            set { _api = value; }
        }

        [JsonProperty( "restful", DefaultValueHandling = DefaultValueHandling.Ignore )]
        [DefaultValue( false )]
        [Description( "Defaults to false. Set to true to operate in a RESTful manner.\nNote: this parameter will automatically be set to true if the Ext.data.Store it is plugged into is set to restful: true. If the Store is RESTful, there is no need to set this option on the proxy." )]
        public bool Restful { get; set; }

        [JsonProperty( "headers" )]
        [DefaultValue( ( string ) null )]
        [JsonConverter( typeof( NotQuotedJsonStringConverter ) )]
        public string Headers { get; set; }

        public bool ShouldSerializeApi()
        {
            return !string.IsNullOrWhiteSpace( Api.Create ) || !string.IsNullOrWhiteSpace( Api.Destroy ) || !string.IsNullOrWhiteSpace( Api.Read ) || !string.IsNullOrWhiteSpace( Api.Update );
        }

        public void ResetApi()
        {
            Api.Create = null;
            Api.Destroy = null;
            Api.Read = null;
            Api.Update = null;
        }
    }
}
